package cn.ctodb.wxmp.service;

import cn.ctodb.wxmp.config.MpConstants;
import cn.ctodb.wxmp.domain.Menu;
import cn.ctodb.wxmp.domain.Mp;
import cn.ctodb.wxmp.repository.MenuRepository;
import cn.ctodb.wxmp.repository.MpRepository;
import cn.ctodb.wxmp.repository.search.MenuSearchRepository;
import cn.ctodb.wxmp.service.dto.MenuDTO;
import cn.ctodb.wxmp.service.mapper.MenuMapper;
import cn.ctodb.wxmp.util.HttpUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;

/**
 * Service Implementation for managing Menu.
 */
@Service
@Transactional
public class MenuService {

    private final Logger log = LoggerFactory.getLogger(MenuService.class);

    @Inject
    private MenuRepository menuRepository;

    @Inject
    private MenuMapper menuMapper;

    @Inject
    private MenuSearchRepository menuSearchRepository;

    @Inject
    private TokenService tokenService;

    @Inject
    private MpRepository mpRepository;

    /**
     * Save a menu.
     *
     * @param menuDTO the entity to save
     * @return the persisted entity
     */
    public MenuDTO save(MenuDTO menuDTO) {
        log.debug("Request to save Menu : {}", menuDTO);
        Menu menu = menuMapper.menuDTOToMenu(menuDTO);
        menu = menuRepository.save(menu);
        MenuDTO result = menuMapper.menuToMenuDTO(menu);
        menuSearchRepository.save(menu);
        return result;
    }

    /**
     * Get all the menus.
     *
     * @param pageable the pagination information
     * @return the list of entities
     */
    @Transactional(readOnly = true)
    public Page<MenuDTO> findAll(Pageable pageable) {
        log.debug("Request to get all Menus");
        Page<Menu> result = menuRepository.findAll(pageable);
        return result.map(menu -> menuMapper.menuToMenuDTO(menu));
    }

    /**
     * Get one menu by id.
     *
     * @param id the id of the entity
     * @return the entity
     */
    @Transactional(readOnly = true)
    public MenuDTO findOne(Long id) {
        log.debug("Request to get Menu : {}", id);
        Menu menu = menuRepository.findOne(id);
        MenuDTO menuDTO = menuMapper.menuToMenuDTO(menu);
        return menuDTO;
    }

    /**
     * Delete the  menu by id.
     *
     * @param id the id of the entity
     */
    public void delete(Long id) {
        log.debug("Request to delete Menu : {}", id);
        menuRepository.delete(id);
        menuSearchRepository.delete(id);
    }

    /**
     * Search for the menu corresponding to the query.
     *
     * @param query the query of the search
     * @return the list of entities
     */
    @Transactional(readOnly = true)
    public Page<MenuDTO> search(String query, Pageable pageable) {
        log.debug("Request to search for a page of Menus for query {}", query);
        Page<Menu> result = menuSearchRepository.search(queryStringQuery(query), pageable);
        return result.map(menu -> menuMapper.menuToMenuDTO(menu));
    }

    public void deleteMenu(Long id) {
        Mp mp = mpRepository.getOne(id);
        String accessToken = tokenService.getAccessToken(id).getAccessToken();
        String doJsonPost = HttpUtils.get(MpConstants.MENU_DELETE_URL + accessToken);
        try {
            JSONObject json = new JSONObject(doJsonPost);
            int errcode = json.getInt("errcode");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void createMenu(Long id) {
        Mp mp = mpRepository.getOne(id);
        String accessToken = tokenService.getAccessToken(id).getAccessToken();
        deleteMenu(id);
        String param = menuToJson(mp.getMenu().getMenus());
        log.debug(param);
        String re = HttpUtils.postJson(MpConstants.MENU_CREATE_URL + accessToken, param);
        log.debug(re);
    }

    private String menuToJson(Set<Menu> menus) {
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (Menu menu : menus) {
            try {
                JSONObject json = new JSONObject();
                json.put("name", menu.getName());
                json.put("type", menu.getMenuType().name().toLowerCase());
                json.put("url", menu.getUrl());
                jsonArray.put(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        try {
            jsonObject.put("button", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }
}
